package com.rtx.edi.platform.tableconfig.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rtx.api.utils.MultipleDataSource;
import com.rtx.common.EdiConstant;
import com.rtx.edi.db.service.DbService;
import com.rtx.edi.model.response.EdiResponse;
import com.rtx.edi.platform.ediapi.bean.EdiApi;
import com.rtx.edi.platform.ediapi.service.EdiApiService;
import com.rtx.edi.platform.tableconfig.bean.EdiColumnValueConfig;
import com.rtx.edi.platform.tableconfig.bean.EdiTableConfig;
import com.rtx.edi.platform.tableconfig.mapper.EdiColumnValueConfigMapper;
import com.rtx.edi.platform.tableconfig.mapper.EdiTableConfigMapper;
import com.rtx.edi.platform.tableconfig.service.EdiTableConfigService;

@Service
public class EdiTableConfigServiceImpl extends ServiceImpl<EdiTableConfigMapper, EdiTableConfig> implements EdiTableConfigService{

	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	EdiColumnValueConfigMapper ediColumnValueConfigMapper;
	
//	@Autowired
//	EdiApiMapper ediApiMapper;
	
	@Autowired
	EdiApiService ediApiService;
	
	@Autowired
	DbService dbService;
	
	@Override
	public void selectList(Page<EdiTableConfig> pageParam, EdiTableConfig po) {
		LambdaQueryWrapper<EdiTableConfig> query = Wrappers.lambdaQuery();
		query.eq(EdiTableConfig::getApiid, po.getApiid());
        baseMapper.selectPage(pageParam, query);
	}

	@Override
	public Map<String, Object> queryInitTree(EdiTableConfig dto) {
		LambdaQueryWrapper<EdiTableConfig> query = Wrappers.lambdaQuery();
		query.eq(EdiTableConfig::getApiid, dto.getApiid());
		List<EdiTableConfig> list = baseMapper.selectList(query);
		Map<String,Object> rootTree = new HashMap<String, Object>();
		for(EdiTableConfig config:list) {
			if(EdiConstant.REQUEST_ROOT_NODE.equals(config.getRequestrootnode())) {
				LambdaQueryWrapper<EdiColumnValueConfig> cvcquery = Wrappers.lambdaQuery();
				List<EdiColumnValueConfig> cvcList =  ediColumnValueConfigMapper.selectList(cvcquery);
				rootTree.put("data", cvcList);
			}
		}
		return rootTree;
	}

	@Override
	public EdiResponse addEdiTableConfig(EdiTableConfig dto) {
		try {
			EdiApi ediai  = ediApiService.getById(dto.getApiid());
			
			//校验
			check(dto,ediai);
			
			dto.setId(null);
			this.save(dto);
			
			//是否为报文节点有改动
			if(EdiConstant.EDI_API_TYPE_STD.equals(ediai.getType()) && "true".equals(dto.getActiverequest())) {
				//重新生成报文
				String requestStr = ediApiService.buildStdRequestJson(ediai);
				LambdaUpdateWrapper<EdiApi> ediapiUpd = Wrappers.lambdaUpdate();
				ediapiUpd.set(EdiApi::getRequest, requestStr);
				ediapiUpd.eq(EdiApi::getId, ediai.getId());
				ediApiService.update(null, ediapiUpd);
			}
			return EdiResponse.success();
		} catch (Exception e) {
			logger.info("",e);
			return EdiResponse.failed().returnMgr(e.getMessage());
		}
	}
	
	private void check(EdiTableConfig dto,EdiApi ediai) {
		MultipleDataSource.setDataSourceKey(ediai.getDatasource());
		try {
			List<String> tablenames = dbService.queryAllTableName();
			List<String> upcasetable = tablenames.stream().map(temp->temp.toUpperCase()).collect(Collectors.toList());
			Assert.isTrue(upcasetable.contains(dto.getName()), "表名称不存在");
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}finally {
			MultipleDataSource.ClearDataSourceKey();
		}
		
	};

	@Override
	public EdiResponse editEdiTableConfig(EdiTableConfig dto) {
		try {
			this.updateById(dto);
			EdiTableConfig oldConfig = this.getById(dto.getId());
			
			if(oldConfig.getActiverequest() == null && dto.getActiverequest() == null) {
				return EdiResponse.success();
			}
			
			if(StringUtils.hasLength(oldConfig.getActiverequest())) {
				if(oldConfig.getActiverequest().equals(dto.getActiverequest())) {
					return EdiResponse.success();
				}
			}
			
			if(StringUtils.hasLength(dto.getActiverequest())) {
				if(dto.getActiverequest().equals(oldConfig.getActiverequest())) {
					return EdiResponse.success();
				}
			}
			
			EdiApi ediai  = ediApiService.getById(dto.getApiid());
			
			//校验
			check(dto,ediai);

			//是否为报文节点有改动
			if(EdiConstant.EDI_API_TYPE_STD.equals(ediai.getType()) && "true".equals(dto.getActiverequest())) {
				//重新生成报文
				String requestStr = ediApiService.buildStdRequestJson(ediai);
				LambdaUpdateWrapper<EdiApi> ediapiUpd = Wrappers.lambdaUpdate();
				ediapiUpd.set(EdiApi::getRequest, requestStr);
				ediapiUpd.eq(EdiApi::getId, ediai.getId());
				ediApiService.update(null, ediapiUpd);
			}
			return EdiResponse.success();
		} catch (Exception e) {
			logger.info("",e);
			return EdiResponse.failed().returnMgr(e.getMessage());
		}
	}

	@Override
	public EdiResponse deleteEdiTableConfigByIds(List<EdiTableConfig> list) {
		try {
			 List<Long> ids = list.stream().map(p -> p.getId()).distinct().collect(Collectors.toList());
		     this.removeBatchByIds(ids);
			
			EdiApi ediai  = ediApiService.getById(list.get(0).getApiid());
			//是否为报文节点有改动
			if(EdiConstant.EDI_API_TYPE_STD.equals(ediai.getType())) {
				//重新生成报文
				String requestStr = ediApiService.buildStdRequestJson(ediai);
				LambdaUpdateWrapper<EdiApi> ediapiUpd = Wrappers.lambdaUpdate();
				ediapiUpd.set(EdiApi::getRequest, requestStr);
				ediapiUpd.eq(EdiApi::getId, ediai.getId());
				ediApiService.update(null, ediapiUpd);
			}
			return EdiResponse.success();
		} catch (Exception e) {
			logger.info("",e);
			return EdiResponse.failed().returnMgr(e.getMessage());
		}
	}
}
